<?php

// 创建WebSocket Server对象，监听0.0.0.0:9502端口
$ws = new Swoole\WebSocket\Server('0.0.0.0', 9502);

// 监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
    $data = [
        'user' => "系统消息",
        'content' => $request->fd . '进入直播间',
    ];
    // 给所有连接用户推送消息
    foreach ($ws->connections as $fd) {
        if ($fd != $request->fd) {
            $ws->push($fd, json_encode($data));
        }
    }
});

// 监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
    $data = [
        'user' => "用户" . $frame->fd,
        'content' => $frame->data,
    ];
    // 给所有连接用户推送消息
    foreach ($ws->connections as $fd) {
        $ws->push($fd, json_encode($data));
    }
});

// 监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
    $data = [
        'user' => "系统消息",
        'content' => $fd . '退出直播间',
    ];
    // 给所有连接用户推送消息
    foreach ($ws->connections as $id) {
        if ($fd != $id) {
            $ws->push($id, json_encode($data));
        }
    }
    echo "client-{$fd} is closed\n";
});

$ws->start();

